package tcp

import (
	"context"
	"core/id"
	"encoding/hex"
	getty "github.com/apache/dubbo-getty"
	"github.com/dubbogo/gost/log/logger"
	"iotall/iotcore/api/proxyup"
	"iotall/iotcore/entity"
	"iotall/iotproxy/pkg"
	"iotall/iotproxy/proxyconfig"
	dataserver2 "iotall/iotproxy/server/dataserver"

	"time"
)

type PkgHandler struct {
	Server *TcpServer
}

func (h *PkgHandler) Read(session getty.Session, data []byte) (interface{}, int, error) {
	session.SetAttribute("LstRev", time.Now())
	var Sid = session.GetAttribute("Sid").(string)
	var ReqId = id.NewId()
	var in = &proxyup.UpReq{
		ReqId:       ReqId,
		Sid:         Sid,
		RemoteAddr:  session.RemoteAddr(),
		CommPortId:  h.Server.CommPort.Id,
		CommProxyId: proxyconfig.Config.Id,
		Data:        data,
		P1:          "",
		P2:          "",
		P3:          "",
		P4:          "",
	}
	var mrev = &entity.CommData{
		Id:         ReqId,
		Sid:        Sid,
		Method:     "上传",
		CrtDt:      time.Now(),
		Data:       hex.EncodeToString(data),
		Memo:       "",
		CommPortId: h.Server.CommPort.Id,
	}
	var resp, err = pkg.ProxyUpClientImpl.Up(context.Background(), in)
	if err != nil {
		logger.Errorf("onUp %v", err)
		mrev.Memo = "解析失败" + err.Error()
	} else {
		mrev.Memo = resp.Msg

		mrev.Sid = resp.Sid
	}
	//保存上传日志
	dataserver2.CommDataServer.AddData(mrev)

	if err != nil {

	} else {
		if resp.Ok {
			//上传连接信息
			if Sid == "" && resp.Sid != Sid {
				var CrtDt = session.GetAttribute("CrtDt").(time.Time)
				dataserver2.ConnectInfoServer.Add(id.NewId(), h.Server.CommPort.Id, resp.Sid, session.RemoteAddr(), "连接", CrtDt)
			}
			if resp.Sid != "" && resp.Sid != Sid {
				Sid = resp.Sid
				session.SetAttribute("Sid", Sid)
			}

			if len(resp.Data) > 0 {
				var msend = &entity.CommData{
					Id:         id.NewId(),
					Sid:        Sid,
					Method:     "下发",
					CrtDt:      time.Now(),
					Data:       hex.EncodeToString(resp.Data),
					Memo:       resp.DownMsg,
					CommPortId: h.Server.CommPort.Id,
				}
				_, err = session.WriteBytes(resp.Data)
				if err != nil {
					msend.Memo += " 下发失败"
				}
				//保存下发日志
				dataserver2.CommDataServer.AddData(msend)
			}
		} else {
			session.Close()
		}
	}

	return data, len(data), nil

}

func (h *PkgHandler) Write(ss getty.Session, pkg interface{}) ([]byte, error) {
	buf := make([]byte, 10)
	return buf, nil
}
